package com.zf.yichat.controller.group;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.dto.RcGroupsDto;
import com.zf.yichat.dto.im.GroupMemberListDto;
import com.zf.yichat.dto.response.BalanceUserDto;
import com.zf.yichat.dto.response.GroupCreateAuthDto;
import com.zf.yichat.im.mapper.RcGroupMembersMapper;
import com.zf.yichat.im.mapper.RcGroupsMapper;
import com.zf.yichat.mapper.AppConfigMapper;
import com.zf.yichat.mapper.GroupManageMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.GroupService;
import com.zf.yichat.service.ImApiService;
import com.zf.yichat.service.TbArticleService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.common.*;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 11:56 2019/7/29 2019
 */
@Controller
@RequestMapping("group")
public class GroupController extends BaseController {


    @Resource
    private RcGroupsMapper rcGroupsMapper;

    @Resource
    private RcGroupMembersMapper rcGroupMembersMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ImApiService imApiService;

    @Autowired
    private AppConfigMapper appConfigMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GroupService groupService;

    @Autowired
    private TbArticleService tbArticleService;

    @Resource
    private GroupManageMapper groupManageMapper;

    @Value("${st.im_uri}")
    private String imUri;


    /**群组管理-访问页面方法开始*/
    /**
     * 文章管理-访问页面方法
     * @return
     */
    @RequestMapping("/article/index")
    public String articleIndex() {
        return "group/article/index";
    }

    /**
     * 文章管理-新增页面
     * @return
     */
    @RequestMapping("/article/save")
    public String articleSave(Integer id) {
        if (null != id) {
            TbArticle tbArticle = tbArticleService.selectArticleById(id);
            getRequest().setAttribute("article", tbArticle);
        }
        return "group/article/save";
    }

    /**
     * 文章管理-展示页面
     * @return
     */
    @RequestMapping("/article/show")
    public String articleShow() {
        return "group/article/show";
    }



    @RequestMapping("/index")
    public String index() {
        return "group/index";
    }

    /**
     * 社群列表
     * @return
     */
    @RequestMapping("/associationList")
    public String associationList() {
        return "group/association/list";
    }

    /**
     * 社群列表-新增
     * @return
     */
    @RequestMapping("/associationAdd")
    public String associationAdd() {
        return "group/association/add";
    }

    /**
     * 社群列表-编辑
     * @return
     */
    @RequestMapping("/associationEdit")
    public String associationEdit(Integer id) {
        GroupManage manage = groupManageMapper.selectByPrimaryKey(id);
        getRequest().setAttribute("manage", manage);
        return "group/association/edit";
    }

    @RequestMapping("/list")
    @ResponseBody
    public FsResponse list(Integer page, Integer limit, String name) {
        if (!(boolean) getRequest().getSession().getAttribute("isAdmin")) {
            DtoChangeUtils.getPageList(new ArrayList<>(), v -> v);
        }

        Example example = new Example(RcGroups.class);
        if (StringUtils.isNotBlank(name)) {
            example.createCriteria().andLike("name", "%" + name + "%");
        }
        example.setOrderByClause(" createdAt desc");
        PageHelper.startPage(page, limit);
        List<RcGroups> list = rcGroupsMapper.selectListByName(name);
        return DtoChangeUtils.getPageList(list, v -> {
            try {
                Integer creatorid = v.getCreatorid();
                User user = userMapper.queryUserByParam("", creatorid.longValue());

                RcGroupsDto groupsDto = new RcGroupsDto();
                groupsDto.setGroupIdEncryption(N3d.encode(Long.valueOf(v.getId())));
                BeanUtils.copyProperties(v, groupsDto);
                groupsDto.setGroupLeaderName(user.getNick());
                return groupsDto;
            } catch (Exception e) {
            }
            return v;
        });
    }

    @RequestMapping("member/index")
    public String memberIndex(Integer gid) {
        getRequest().setAttribute("gid", gid);
        return "group/member";
    }

    /**
     * 群组成员列表
     * @param page
     * @param limit
     * @param gid
     * @return
     */
    @RequestMapping("member/list")
    @ResponseBody
    public FsResponse memberList(Integer page, Integer limit, Integer gid) {
        if (!(boolean) getRequest().getSession().getAttribute("isAdmin")) {
            DtoChangeUtils.getPageList(new ArrayList<>(), v -> v);
        }

        Example example = new Example(RcGroupMembers.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("groupid", gid);
        criteria.andEqualTo("isdeleted", RcGroupMembers.IS_DELETED_NO);
        example.setOrderByClause(" createdat desc");
        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(rcGroupMembersMapper.selectByExample(example), copy -> {
            GroupMemberListDto listDto = new GroupMemberListDto();

            User user = userService.selectById(copy.getMemberid().longValue());
            if (Objects.nonNull(user)) {
                listDto.setUserName(user.getNick());
                listDto.setUserAvatar(user.getAvatar());
            }

            listDto.setId(copy.getId());
            listDto.setGroupid(copy.getGroupid());
            listDto.setMemberid(copy.getMemberid());
            try {
                listDto.setUserIdStr(N3d.encode(Long.valueOf(copy.getMemberid())));
            } catch (Exception e) {
            }
            listDto.setTimestamp(copy.getTimestamp());

            return listDto;

        });
    }

    /**
     * 文章列表
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @RequestMapping("article/list")
    @ResponseBody
    public FsResponse articleList(Integer page, Integer limit, String name) {
        return tbArticleService.selectIndexList(FsPage.init(page, limit), name);
    }

    /**
     * 文章新增功能
     * @param article
     * @return
     */
    @RequestMapping("article/saveArticle")
    @ResponseBody
    public FsResponse saveArticle(TbArticle article) {
        return FsResponseGen.gen(tbArticleService.saveArticle(article) == 1);
    }

    /**
     * 文章删除功能
     * @param id
     * @return
     */
    @RequestMapping("article/clean")
    @ResponseBody
    public FsResponse cleanArticle(Integer id) {
        tbArticleService.deleteArticle(id);
        return FsResponseGen.success();
    }

    /**
     * 根据用户查询所在群组
     * @param page
     * @param limit
     * @param userId
     * @return
     */
    @RequestMapping("member/groupList")
    @ResponseBody
    public FsResponse groupList(Integer page, Integer limit, Long userId) {

        PageHelper.startPage(page, limit);
        List<RcGroups> groupMembersList = rcGroupMembersMapper.queryGroupByMemberId(userId);
        return DtoChangeUtils.getPageList(groupMembersList, copy -> {
            try {
                Integer creatorid = copy.getCreatorid();
                User user = userMapper.queryUserByParam("", creatorid.longValue());

                RcGroupsDto groupsDto = new RcGroupsDto();
                groupsDto.setGroupIdEncryption(N3d.encode(Long.valueOf(copy.getId())));
                BeanUtils.copyProperties(copy, groupsDto);
                groupsDto.setGroupLeaderName(user.getNick());
                return groupsDto;
            } catch (Exception e) {
            }
            return copy;
        });
    }

    /**
     * 群封禁
     * @param groupId
     * @param status
     * @return
     */
    @RequestMapping("mute")
    @ResponseBody
    public FsResponse muteAll(Integer groupId, Integer status) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "gdjaiogegslgndksnglds");
        try {
            jsonObject.put("groupId", N3d.encode(Long.valueOf(groupId)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("muteStatus", status);
        String result = OKHttpUtil.httpPostJson(imUri + "group/mute_feng", jsonObject.toJSONString());
        if (Objects.isNull(result)) {
            return FsResponseGen.failMsg("融云服务器异常");
        } else {
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 200) {
                return FsResponseGen.success();
            } else {
                return FsResponseGen.failMsg(resultJson.getString("message"));
            }
        }
    }

    /**
     * 群解散
     * @param groupId
     * @return
     */
    @RequestMapping("dismiss")
    @ResponseBody
    public FsResponse dismiss(Integer groupId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "CltgSmLjo2UnnZJlSrEAy");
        try {
            jsonObject.put("groupId", N3d.encode(Long.valueOf(groupId)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = OKHttpUtil.httpPostJson(imUri + "group/dismiss_back", jsonObject.toJSONString());
        if (Objects.isNull(result)) {
            return FsResponseGen.failMsg("融云服务器异常");
        } else {
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 200) {
                return FsResponseGen.success();
            } else {
                return FsResponseGen.failMsg(resultJson.getString("message"));
            }
        }
    }


    @RequestMapping("member/delete")
    @ResponseBody
    public FsResponse memberDelete(Long uid, Integer gid) {
        imApiService.deleteGroupMember(gid, uid);
        return FsResponseGen.success();
    }

    /**
     * 移除群成员
     * 1. 调用融云退群接口
     * 2. 将group_members表的isDeleted
     * @param uid
     * @param gid
     * @return
     */
    @RequestMapping("member/quit")
    @ResponseBody
    public FsResponse memberQuit(Long uid, Integer gid) {
        try {
            groupService.memberQuit(uid, gid);
            return FsResponseGen.successMsg("移除成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.failMsg("移除失败！");
    }

    @RequestMapping("create/auth/index")
    public String authIndex() {
        Example select = new Example(AppConfig.class);
        select.createCriteria().andEqualTo("type", 0);

        getRequest().setAttribute("type", appConfigMapper.selectCountByExample(select) > 0 ? 0 : 1);
        return "group/auth";
    }

    @RequestMapping("create/auth/list")
    @ResponseBody
    public FsResponse authList(Integer page, Integer limit) {

        Example select = new Example(AppConfig.class);
        select.createCriteria().andEqualTo("type", 0);
        select.setOrderByClause(" id desc");
        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(appConfigMapper.selectByExample(select), copy -> {
            GroupCreateAuthDto dto = new GroupCreateAuthDto();

            User user = userService.selectById((copy.getUserId()));
            if (Objects.nonNull(user)) {
                dto.setNick(user.getNick());
                dto.setAvatar(user.getAvatar());
                dto.setUserId(copy.getUserId());
            }

            dto.setId(copy.getId());
            dto.setCtime(DateUtils.formatDate(copy.getCtime()));

            return dto;

        });
    }

    @RequestMapping("create/auth/delete")
    @ResponseBody
    public FsResponse authDelete(Integer type, String ids) {

        if (type == 0) {
            Example select = new Example(AppConfig.class);
            appConfigMapper.deleteByExample(select);
        } else {
            GeneralUtils.splitExcludeEmpty(ids).forEach(v -> {

                appConfigMapper.deleteByPrimaryKey(v);
            });
        }
        return FsResponseGen.success();
    }


    @RequestMapping("create/auth/add")
    @ResponseBody
    public FsResponse authAdd(Long userId) {

        AppConfig config = new AppConfig();
        //appConfigMapper.insertSelective()
        return FsResponseGen.success();
    }

    @RequestMapping("choose")
    @ResponseBody
    public String choose(Long userId) {


        return "group/user";
    }

    @RequestMapping("user/list")
    @ResponseBody
    public FsResponse userList(Integer page, Integer limit, String name, Integer status, String mobile, String ucode) {

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("status", 0);
        if (StringUtils.isNotBlank(name)) {
            criteria.andLike("nick", "%" + name + "%");
        }
        if (StringUtils.isNotBlank(mobile)) {
            criteria.andLike("mobile", "%" + mobile + "%");
        }
        if (StringUtils.isNotBlank(ucode)) {
            criteria.andEqualTo("appid", ucode);
        }
        example.setOrderByClause(" id desc");
        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(userMapper.selectByExample(example), copy -> {
            BalanceUserDto dto = new BalanceUserDto();

            User user = userService.selectById(copy.getId());
            dto.setNick(user.getNick());
            dto.setUserId(copy.getId());
            dto.setAvatar(copy.getAvatar());
            dto.setMobile(copy.getMobile());
            dto.setAppId(copy.getAppid());
            dto.setCtime(copy.getCtime());
            //dto.setBalance(balanceService.selectByUserId(copy.getId()).getBalance());

            return dto;
        });
    }

    /**
     * 社群管理列表
     * @param page
     * @param limit
     * @param groupName
     * @return
     */
    @RequestMapping("/groupManageList")
    @ResponseBody
    public FsResponse groupManageList(Integer page, Integer limit, String groupName) {

        Example example = new Example(GroupManage.class);
        if (StringUtils.isNotBlank(groupName)) {
            example.createCriteria().andLike("groupName", "%" + groupName + "%");
        }
        example.setOrderByClause(" ctime desc");
        PageHelper.startPage(page, limit);

        List<GroupManage> list = groupManageMapper.selectByExample(example);
        return DtoChangeUtils.getPageList(list, data -> {
            GroupManage manage = new GroupManage();
            BeanUtils.copyProperties(data, manage);
            return manage;
        });
    }

    /**
     * 新增社群管理
     * @return
     */
    @RequestMapping("/groupManageAdd")
    @ResponseBody
    public FsResponse groupManageAdd(GroupManage manage) {
        try {
            Integer groupId = manage.getGroupId();
            String encryptGroupId = N3d.encode(Long.valueOf(groupId));
            manage.setEncryptGroupId(encryptGroupId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        groupManageMapper.insertSelective(manage);
        return FsResponseGen.success();
    }

    /**
     * 编辑社群管理
     * @return
     */
    @RequestMapping("/groupManageEdit")
    @ResponseBody
    public FsResponse groupManageEdit(GroupManage manage) {
        try {
            Integer groupId = manage.getGroupId();
            String encryptGroupId = N3d.encode(Long.valueOf(groupId));
            manage.setEncryptGroupId(encryptGroupId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        groupManageMapper.updateByPrimaryKeySelective(manage);
        return FsResponseGen.success();
    }

    /**
     * 编辑社群管理
     * @return
     */
    @RequestMapping("/associationDel")
    @ResponseBody
    public FsResponse associationDel(Integer manageId) {
        groupManageMapper.deleteByPrimaryKey(manageId);
        return FsResponseGen.success();
    }
}
